package live.zs.elastic.controller;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import live.zs.elastic.entity.Person;
import live.zs.elastic.repository.PersonRepository;
import org.elasticsearch.client.RestClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author madison
 * {@code @description}
 * {@code @date} 2023/5/2 17:14
 */
@RestController
@RequestMapping("elastic")
public class IndexController {
    private final Logger logger = LoggerFactory.getLogger(IndexController.class);
    @Autowired
    ElasticsearchOperations operations;
    @Autowired
    private PersonRepository personRepository;
    @Autowired
    ElasticsearchClient elasticsearchClient;
    @Autowired
    RestClient restClient;

    @GetMapping("index")
    public List<String> index() {
        SearchHits<Person> search = operations.search(Query.findAll(), Person.class);
        logger.info("search res:{}", search);
        for (SearchHit<Person> searchHits : search.getSearchHits()) {
            logger.info("hits index: {}, id: {}, content: {}", searchHits.getIndex(), searchHits.getId(), searchHits.getContent());
        }
        return new ArrayList<>();
    }

    @PostMapping("person")
    public String save(@RequestBody Person person) {
        Person savedEntity = operations.save(person);
        return savedEntity.getId();
    }

    @GetMapping("person/{id}")
    public Person findById(@PathVariable("id") String id) {
        return operations.get(id, Person.class);
    }

    @GetMapping("personRepo/{id}")
    public Person findByRepoId(@PathVariable("id") String id) {
        return personRepository.findById(id).get();
    }

    @GetMapping("client")
    public List<String> client() {
//        elasticsearchClient.search(SearchRequest.);
        return new ArrayList<>();
    }
}
